package com.secxiot.common.utils;


import com.gexin.fastjson.JSONObject;
import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.entity.WXMessage;
import com.secxiot.common.exception.BaseRuntimeException;
import com.secxiot.provider.user.vo.WxAppVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具
 */
@Component
public class WeChatUtil {
    public static String httpRequest(String requestUrl, String requestMethod, String output) {
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            if (null != output) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes("utf-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    public static JSONObject getOpenIdByCode(String code, WxAppVo wxAppVo) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 根据小程序穿过来的code想这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppVo.getAppId() + "&secret=" + wxAppVo.getAppSecrt() + "&js_code=" + code + "&grant_type=authorization_code";
        // 发送请求，返回Json字符串
        String str = WeChatUtil.httpRequest(url, "GET", null);
        return JSONObject.parseObject(str);
    }

    /**
     * 获取access_token
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public static JSONObject getAccessToken(String appId, String appSecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String str = WeChatUtil.httpRequest(url, "GET", null);
        JSONObject jsonObject = JSONObject.parseObject(str);
        int errcode = jsonObject.getIntValue("errcode");
        if(errcode != 0){
            if(errcode == -1){
                throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_1);
            } else if (errcode == 40001){
                throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_2);
            } else if (errcode == 40002){
                throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_3);
            } else if (errcode == 40003){
                throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_4);
            }
        }
        return jsonObject;
    }

    /**
     * 发送消息
     *
     * @param wxMessage
     * @return
     */
    public static JSONObject sendSubscribeMessage(WXMessage wxMessage) {
        String access_token = wxMessage.getAccess_token();
        if(!StringUtils.isEmpty(wxMessage.getAppId()) && !StringUtils.isEmpty(wxMessage.getAppSecret())){
            JSONObject accessToken = getAccessToken(wxMessage.getAppId(), wxMessage.getAppSecret());
            access_token = accessToken.getString("access_token");
        }

        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token + "&touser=" + wxMessage.getTouser()
                + "&template_id=" + wxMessage.getTemplate_id() + "&data=" +wxMessage.getData();
        String str = WeChatUtil.httpRequest(url, "GET", null);

        JSONObject jsonObject = JSONObject.parseObject(str);
        int errcode = jsonObject.getIntValue("errcode");
        if(errcode == 40003){
            throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_5);
        } else if (errcode == 40037){
            throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_6);
        } else if (errcode == 43101){
            throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_7);
        } else if (errcode == 47003){
            throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_8);
        } else if (errcode == 41030){
            throw new BaseRuntimeException(ServerStatusEnum.WX_ERROR_9);
        }
        return jsonObject;
    }
}
